package com.yingxin.yxerp.module.common.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class Pinyin4jUtil {

    private static Logger logger = LoggerFactory.getLogger(Pinyin4jUtil.class);

    /**
     * 获取中文拼音首字母
     *
     * @param str
     */
    public static String getInitials(String str) {
        HanyuPinyinOutputFormat pof = new HanyuPinyinOutputFormat();
        //大写
        pof.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        //声调格式
        pof.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        char[] charArray = str.toCharArray();
        String initials = null;
        //匹配中文,非中文转换会转换成null
        if (Character.toString(charArray[0]).matches("[\\u4E00-\\u9FA5]+")) {
            try {
                String[] strArray = PinyinHelper.toHanyuPinyinStringArray(charArray[0], pof);
                initials = String.valueOf(strArray[0].charAt(0));
            } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                logger.error("获取中文首字母异常");
            }
        } else if (Character.toString(charArray[0]).matches("[a-z]+")) {
            //小写字母
            initials = String.valueOf(charArray[0]).toUpperCase();
        } else if (Character.toString(charArray[0]).matches("[A-Z]+")) {
            //大写字母
            initials = String.valueOf(charArray[0]);
        }
        return initials;
    }

    public static void main(String[] args) throws IOException {
    }

}
